package org.yylnb.openplatform.gateway.bean;

import org.springframework.stereotype.Component;
import org.yylnb.openplatform.commons.constans.ApiTagInRedis;
import org.yylnb.openplatform.commons.utlis.CommonsResult;
import org.yylnb.openplatform.gateway.api.CacheService;
import org.yylnb.openplatform.gateway.utils.LocalCacheUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * @author RainLin
 * @date 2020/7/25 - 18:16
 */
@Component
public class InitLocalCacheBean {
    private final CacheService cacheService;

    public InitLocalCacheBean(CacheService cacheService) {
        this.cacheService = cacheService;
    }


    @PostConstruct
    public void init() {
        //TODO 20200727 发现一个问题,我们需要在这里不仅仅是查询路由信息,可能还要预先加载一部分应用信息和客户信息进来,可能会消耗大量的时间,导致程序可能会暂停,不合适
        //TODO 可以使用线程异步去请求数据
        new Thread() {
            @Override
            public void run() {
                loadData(ApiTagInRedis.API_MAPPING);
                loadData(ApiTagInRedis.API_CUSTOMER);
                loadData(ApiTagInRedis.APP_INFO);

            }
        }.start();
    }

    private void loadData(String apiTagInRedis) {
        //从缓存中加载数据到本地缓存,先找现在redis中和路由相关的key有哪些
        CommonsResult<List<String>> keysResultAboutTagInRedis = cacheService.getKeys(apiTagInRedis + "*");
        List<String> keys = keysResultAboutTagInRedis.getData();
        //遍历所有的key,然后加载对应的路由信息
        for (String key : keys) {
            CommonsResult<Map<String, String>> result = cacheService.hGetAll(key);
            //拿到当前key对应的路由信息
            Map<String, String> resultMap = result.getData();
            LocalCacheUtils.addMapping(key,resultMap);
        }
        System.err.println(LocalCacheUtils.getApiRoutingMap());
        //按照预定的方式保存到本地缓存中
    }

}
